<?php
error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('America/New_York');
ini_set('display_errors', 1);
set_time_limit(60*30);
ini_set('memory_limit', '256M');

require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';

$g_start = microtime(true);

$dbconn = Connection::getInstance();

$sites = getSites($dbconn);
foreach ($sites as $site)
{
	if ($site['domain'] == 'lalaloot.com') 
	{
		$users = getWhaleUsers($dbconn, $site['id'], 50);
		echo (microtime(true)-$g_start) . "\tlalaloot\t". count($users). " users\n";
		$lalalootWhales = reverseIdAsKey($users);
		echo (microtime(true)-$g_start) . "\tlalaloot\treverse key\n";
		foreach ($lalalootWhales as $id => &$lalalootWhale)
		{
			$whale = getMinCompletedTime($dbconn, $id);
			if (count($whale)>0)
			{
				$lalalootWhale['user_created'] = $whale[0]['user_created'];
				$lalalootWhale['offer_created'] = $whale[0]['offer_created'];
			}
		}
		echo (microtime(true)-$g_start) . "\tlalaloot\tcompleted time\n";
		$lalalootWhales = getUserConfirmLongRegTime($lalalootWhales);
		echo (microtime(true)-$g_start) . "\tlalaloot\tconfirm & long reg\n";
		$lalalootResult = calculateCompletedTime($lalalootWhales);
		echo (microtime(true)-$g_start) . "\tlalaloot\tcalculate\n";
		$formattedResult = formatEcho($lalalootResult);
		echo (microtime(true)-$g_start) . "\tlalaloot Result:\n";
		echo $formattedResult ;
		
		
		
		$users = getNonRewardsUsers($dbconn, $site['id']);
		echo "-- No rewards record users Lalaloot -- \n";
		echo (microtime(true)-$g_start) . "\tlalaloot\t". count($users). " users\n";
		$lalalootWhales = reverseIdAsKey($users);
		echo (microtime(true)-$g_start) . "\tlalaloot\treverse key\n";
		foreach ($lalalootWhales as $id => &$lalalootWhale)
		{
			$whale = getMinCompletedTime($dbconn, $id);
			if (count($whale)>0)
			{
				$lalalootWhale['user_created'] = $whale[0]['user_created'];
				//$lalalootWhale['offer_created'] = $whale[0]['offer_created'];
			}
		}
		echo (microtime(true)-$g_start) . "\tlalaloot\tcompleted time\n";
		$lalalootWhales = getUserConfirmLongRegTime($lalalootWhales);
		echo (microtime(true)-$g_start) . "\tlalaloot\tconfirm & long reg\n";
		$lalalootResult = calculateCompletedTime($lalalootWhales);
		echo (microtime(true)-$g_start) . "\tlalaloot\tcalculate\n";
		$formattedResult = formatEcho($lalalootResult);
		echo (microtime(true)-$g_start) . "\tlalaloot Result:\n";
		echo $formattedResult ;
		
		
		
	}
	else if ($site['domain'] == 'cashdazzle.com') 
	{
		$users = getWhaleUsers($dbconn, $site['id'], 15);
		echo (microtime(true)-$g_start) . "\tcashdazzle\t". count($users). " users\n";
		$cashdazzleWhales = reverseIdAsKey($users);
		echo (microtime(true)-$g_start) . "\tcashdazzle\treverse key\n";
		foreach ($cashdazzleWhales as $id => &$cashdazzleWhale)
		{
			$whale = getMinCompletedTime($dbconn, $id);
			if (count($whale)>0)
			{
				$cashdazzleWhale['user_created'] = $whale[0]['user_created'];
				$cashdazzleWhale['offer_created'] = $whale[0]['offer_created'];
			}
		}
		echo (microtime(true)-$g_start) . "\tcashdazzle\tcompleted time\n";
		$cashdazzleWhales = getUserConfirmLongRegTime($cashdazzleWhales);
		echo (microtime(true)-$g_start) . "\tcashdazzle\tconfirm & long reg\n";
		$cashdazzleResult = calculateCompletedTime($cashdazzleWhales);
		echo (microtime(true)-$g_start) . "\tcashdazzle\tcalculate\n";
		$formattedResult = formatEcho($cashdazzleResult);
		echo (microtime(true)-$g_start) . "\tcashdazzle Result:\n";
		echo $formattedResult;
		
		
		
		$users = getNonRewardsUsers($dbconn, $site['id']);
		echo "-- No rewards record users Cashdazzle -- \n";
		echo (microtime(true)-$g_start) . "\tcashdazzle\t". count($users). " users\n";
		$cashdazzleWhales = reverseIdAsKey($users);
		echo (microtime(true)-$g_start) . "\tcashdazzle\treverse key\n";
		foreach ($cashdazzleWhales as $id => &$cashdazzleWhale)
		{
			$whale = getMinCompletedTime($dbconn, $id);
			if (count($whale)>0)
			{
				$cashdazzleWhale['user_created'] = $whale[0]['user_created'];
				//$cashdazzleWhale['offer_created'] = $whale[0]['offer_created'];
			}
		}
		echo (microtime(true)-$g_start) . "\tcashdazzle\tcompleted time\n";
		$cashdazzleWhales = getUserConfirmLongRegTime($cashdazzleWhales);
		echo (microtime(true)-$g_start) . "\tcashdazzle\tconfirm & long reg\n";
		$cashdazzleResult = calculateCompletedTime($cashdazzleWhales);
		echo (microtime(true)-$g_start) . "\tcashdazzle\tcalculate\n";
		$formattedResult = formatEcho($cashdazzleResult);
		echo (microtime(true)-$g_start) . "\tcashdazzle Result:\n";
		echo $formattedResult;
	}
}
//$rewardItems = getEachUserMinCompletedTime($dbconn);
//$reversedRewardItems = reverseIdAsKey($rewardItems);
//$usersWithConfirmLongRegTime = getUserConfirmLongRegTime($reversedRewardItems);
//$result = calculateCompletedTime($usersWithConfirmLongRegTime);
//$formattedResult =  formatEcho($result);


//echo $formattedResult;




//$handler = fopen(dirname(__FILE__) . '/stat_rewards', 'w+');
//fwrite($handler, $formattedResult);

function getSites(Connection $db)
{
	$sql = "SELECT id, domain FROM `sites` ";
	try{
		$ret = $db->query($sql);
		return $ret;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function getWhaleUsers(Connection $db, $site_id, $tokenAmount)
{
	$sql = "SELECT u.id, SUM(r.credit) AS total_t FROM `users` AS u LEFT JOIN `rewards` AS r ON u.id=r.user_id WHERE u.site_id=? and u.created>=1320120000 and u.created<1322715600 GROUP BY u.id HAVING total_t>=? ORDER BY total_t DESC";
	try{
		$ret = $db->query($sql, array($site_id, $tokenAmount));
		return $ret;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function getNonRewardsUsers(Connection $db, $site_id) {
	$sql = "SELECT u.id, u.created AS user_created FROM users AS u LEFT JOIN rewards AS r ON u.id = r.user_id WHERE u.site_id=? and u.created>=1320120000 and u.created<1322715600 and r.id IS NULL";
	try{
		$ret = $db->query($sql, array($site_id));
		return $ret;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function getMinCompletedTime(Connection $dbconn, $uid)
{
	$sql = "SELECT u.id, u.created as user_created, min(r.created) as offer_created FROM `rewards` r, `users` u where u.id=? and u.id = r.user_id group by user_id";
	try{
		$result = $dbconn->query($sql, array($uid));
		return $result;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}
function getEachUserMinCompletedTime(Connection $dbconn) {
	$sql = "SELECT u.id, u.created as user_created, min(r.created) as offer_created FROM `rewards` r, `users` u where u.id = r.user_id group by user_id";
	try{
		$result = $dbconn->query($sql);
		return $result;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function reverseIdAsKey($rewardItems) {
	$temp = array();
	foreach ($rewardItems as $rewardItem) {
		$temp[$rewardItem['id']] = $rewardItem;
	}
	return $temp;
}

function getUserConfirmLongRegTime($rewardItems) {
	chdir(RAW_DATA_ROOT);
	//loop every month
	foreach (glob("*_*") as $dirname) {
		if (is_dir($dirname)) {
			chdir(RAW_DATA_ROOT . '/' . $dirname);
				foreach (glob("*_*") as $filename) {
					if (count(explode('_', $filename)) == 2) {
						$handler = fopen(RAW_DATA_ROOT . '/' . $dirname . '/' . $filename, 'r');
						if ($handler) {
							
							while (!feof($handler)) {
								$line = fgets($handler);
								if (!empty($line)) {
									$args = explode(':', $line);
									if (!empty($args[4]) && !empty($args[0]) && !empty($args[3]))
									{
										$event = $args[4];
										$uid = $args[3];
										$time = $args[0];
										
										if (isset($rewardItems[$uid])) {
											if ($event == 'confirmed') {
												$rewardItems[$uid]['confirmed'] = $time;
											} elseif ($event == 'full_reg') {
												$rewardItems[$uid]['full_reg'] = $time;
											}
										}
										
									}
								}
							}
							fclose($handler);
						}
					}
				}
			chdir(RAW_DATA_ROOT);
		}
	}
	return $rewardItems;
}


function calculateCompletedTime($rewardItems) {
	
	$totalTime = 0;
	$totalNums = count($rewardItems);
	$withinOneHourNums = 0;
	$withinTwoHoursNums = 0;
	
	
	$totalConfirmTime = 0;
	$withinOneHourConfirmNums = 0;
	$withinTwoHoursConfirmNums = 0;
	
	$totalLongRegTime = 0;
	$withinOneHourLongRegNums = 0;
	$withinTwoHoursLongRegNums = 0;
	
	
	$rewardCompleteList = array();
	$confirmCompleteList = array();
	$longRegCompleteList = array();
	
	$totalBoth = 0;
	$withinOneHourBoth = 0;
	$withinTwoHoursBoth = 0;

	$withinOneHourAny = 0;
	$withinTwoHoursAny = 0;

	foreach ($rewardItems as $rewardItem) {
		if (isset($rewardItem['offer_created']))
		{
			$currentRewardCompletedTime = $rewardItem['offer_created'] - $rewardItem['user_created'];
			$totalTime += $currentRewardCompletedTime;
			$timeCost = (int) ($currentRewardCompletedTime/60);
			$rewardCompleteList[] = $timeCost;
			if ($timeCost <= 60) {
				$withinOneHourNums++;
			} 
			if ($timeCost <= 120) {
				$withinTwoHoursNums++;
			}
		}
		if (isset($rewardItem['confirmed'])) {
			$currentConfirmCompleteTime = $rewardItem['confirmed'] - $rewardItem['user_created'];
			$totalConfirmTime += $currentConfirmCompleteTime;
			$timeCostConfirm = (int) ($currentConfirmCompleteTime/60);
			$confirmCompleteList[] = $timeCostConfirm;
			if ($timeCostConfirm <= 60) {
				$withinOneHourConfirmNums++;
			} 
			if ($timeCostConfirm <= 120) {
				$withinTwoHoursConfirmNums++;
			}
		}
		if (isset($rewardItem['full_reg'])) {
			$currentLongRegCompleteTime = $rewardItem['full_reg'] - $rewardItem['user_created'];
			$totalLongRegTime += $currentLongRegCompleteTime;
			$timeCostLongReg = (int) ($currentLongRegCompleteTime/60);
			$longRegCompleteList[] = $timeCostLongReg;
			if ($timeCostLongReg <= 60) {
				$withinOneHourLongRegNums++;
			} 
			if ($timeCostLongReg <= 120) {
				$withinTwoHoursLongRegNums++;
			}
		}
		if (isset($rewardItem['confirmed']) && isset($rewardItem['full_reg']))
		{
			$totalBoth ++;
			if ($timeCostConfirm<=60 && $timeCostLongReg<=60)
			{
				$withinOneHourBoth ++;
			}
			if ($timeCostConfirm<=120 && $timeCostLongReg<=120)
			{
				$withinTwoHoursBoth ++;
			}
		}
		if ((isset($rewarditem['offer_created']) && $timeCost<=60) || (isset($rewardItem['confirmed']) && $timeCostConfirm<=60) || (isset($rewardItem['full_reg']) && $timeCostLongReg<=60))
		{
			$withinOneHourAny ++;
		}
		if ((isset($rewardItem['offer_created']) && $timeCost<=60) || (isset($rewardItem['confirmed']) && $timeCostConfirm<=120) || (isset($rewardItem['full_reg']) && $timeCostLongReg<=120))
		{
			$withinTwoHoursAny ++;
		}
	}
	
	
	$avarageTime =  sprintf("%d", ($totalTime/($totalNums * 60)));
		
	$avarageTimeConfirm = sprintf("%d", ($totalConfirmTime/($totalNums*60)));
	
	$avarageTimeLongReg = sprintf("%d", ($totalLongRegTime/($totalNums*60)));
	
	$order95 = (int) ($totalNums * 0.95);
	$order90 = (int) ($totalNums * 0.9);
	$order80 = (int) ($totalNums * 0.8);
	
	// get required confirm position
	$totalConfirmNums = count($confirmCompleteList);
	$order95Confrim = (int) ($totalNums * 0.95);
	$order90Confrim = (int) ($totalNums * 0.9);
	$order80Confrim = (int) ($totalNums * 0.8);
	
	// get required long reg position
	$totalLongRegNums = count($longRegCompleteList);
	$order95LongReg = (int) ($totalNums * 0.95);
	$order90LongReg = (int) ($totalNums * 0.9);
	$order80LongReg = (int) ($totalNums * 0.8);
	
	//reward complete
	$withOneHourPercent = sprintf("%.2f", ($withinOneHourNums * 100/ $totalNums));
	$withTwoHoursPercent = sprintf("%.2f", (($withinTwoHoursNums) * 100/ $totalNums));
	
	//confirmed
	$withOneHourPercentConfirmed = sprintf("%.2f", ($withinOneHourConfirmNums * 100/ $totalNums));
	$withinTwoHoursPercentConfirmed = sprintf("%.2f", (($withinTwoHoursConfirmNums) * 100/ $totalNums));
	
	
	//full reg
	$withOneHourPercentLongReg = sprintf("%.2f", ($withinOneHourLongRegNums * 100/ $totalNums));
	$withTwoHoursPercentLongReg = sprintf("%.2f", (($withinTwoHoursLongRegNums) * 100/ $totalNums));
	
	$withinOneHourPercentBoth = sprintf("%.2f", ($withinOneHourBoth * 100 / $totalNums));
	$withinTwoHoursPercentBoth = sprintf("%.2f", ($withinTwoHoursBoth * 100 / $totalNums));

	$withinOneHourPercentAny = sprintf("%.2f", ($withinOneHourAny * 100 / $totalNums));
	$withinTwoHoursPercentAny = sprintf("%.2f", ($withinTwoHoursAny * 100 / $totalNums));

	sort($rewardCompleteList, SORT_NUMERIC);
	sort($confirmCompleteList, SORT_NUMERIC);
//	print_r($confirmCompleteList);
	sort($longRegCompleteList, SORT_NUMERIC);
//	print_r($longRegCompleteList);
	
	$result = array(
		'avarageTime' => $avarageTime,
		'order95' => isset($rewardCompleteList[$order95-1])?$rewardCompleteList[$order95-1]:'N/A',
		'order90' => isset($rewardCompleteList[$order90-1])?$rewardCompleteList[$order90-1]:'N/A',
		'order80' => isset($rewardCompleteList[$order80-1])?$rewardCompleteList[$order80-1]:'N/A',
		'withinOneHourPercent' => $withOneHourPercent,
		'withinTwoHoursPercent' => $withTwoHoursPercent,
		'avarageConfirmedTime' => $avarageTimeConfirm,
		'order95Confirm' => isset($confirmCompleteList[$order95Confrim-1])?$confirmCompleteList[$order95Confrim-1]:'N/A',
		'order90Confirm' => isset($confirmCompleteList[$order90Confrim-1])?$confirmCompleteList[$order90Confrim-1]:'N/A',
		'order80Confirm' => isset($confirmCompleteList[$order80Confrim-1])?$confirmCompleteList[$order80Confrim-1]:'N/A',
		'withinOneHourPercentConfirm' => $withOneHourPercentConfirmed,
		'withinTwoHoursPercentConfirm' => $withinTwoHoursPercentConfirmed,
		'avarageLongRegTime' => $avarageTimeLongReg,
		'order95LongReg' => isset($longRegCompleteList[$order95LongReg-1])?$longRegCompleteList[$order95LongReg-1]:'N/A',
		'order90LongReg' => isset($longRegCompleteList[$order90LongReg-1])?$longRegCompleteList[$order90LongReg-1]:'N/A',
		'order80LongReg' => isset($longRegCompleteList[$order80LongReg-1])?$longRegCompleteList[$order80LongReg-1]:'N/A',
		'withinOneHourPercentLongReg' => $withOneHourPercentLongReg,
		'withinTwoHoursPercentLongReg' => $withTwoHoursPercentLongReg,
		'withinOneHourPercentBoth' => $withinOneHourPercentBoth,
		'withinTwoHoursPercentBoth' => $withinTwoHoursPercentBoth,
		'withinOneHourPercentAny' => $withinOneHourPercentAny,
		'withinTwoHoursPercentAny' => $withinTwoHoursPercentAny,
	);
	
	return $result;
}


function formatEcho($result) {
	$s = '';
	$s .= 'Average Offer Completed Time:' . "\t" . $result['avarageTime'] . " minutes \n"
			. "Fast 95% Offer Completed Time:" . "\t" . $result['order95'] . " minutes \n"
			. "Fast 90% Offer Completed Time:" . "\t" . $result['order90'] . " minutes \n"
			. "Fast 80% Offer Completed Time:" . "\t" . $result['order80'] . " minutes \n"
			. "Offer Completed Within One Hour:" . "\t" . $result['withinOneHourPercent'] . "%\n"
			. "Offer Completed Within Two Hours:" . "\t" . $result['withinTwoHoursPercent'] . "%\n".
			'Average Confirm Completed Time:' . "\t" . $result['avarageConfirmedTime'] . " minutes \n"
			. "Fast 95% Confirm Completed Time:" . "\t" . $result['order95Confirm'] . " minutes \n"
			. "Fast 90% Confirm Completed Time:" . "\t" . $result['order90Confirm'] . " minutes \n"
			. "Fast 80% Confirm Completed Time:" . "\t" . $result['order80Confirm'] . " minutes \n"
			. "Confirm Completed Within One Hour:" . "\t" . $result['withinOneHourPercentConfirm'] . "%\n"
			. "Confirm Completed Within Two Hours:" . "\t" . $result['withinTwoHoursPercentConfirm'] . "%\n".
			'Average Long Reg Completed Time:' . "\t" . $result['avarageLongRegTime'] . " minutes \n"
			. "Fast 95% Long Reg Completed Time:" . "\t" . $result['order95LongReg'] . " minutes \n"
			. "Fast 90% Long Reg Completed Time:" . "\t" . $result['order90LongReg'] . " minutes \n"
			. "Fast 80% Long Reg Completed Time:" . "\t" . $result['order80LongReg'] . " minutes \n"
			. "Long Reg Completed Within One Hour:" . "\t" . $result['withinOneHourPercentLongReg'] . "%\n"
			. "Long Reg Completed Within Two Hours:" . "\t" . $result['withinTwoHoursPercentLongReg'] . "%\n"
			. "Both Confirm and Long Reg Within One Hour:\t". $result['withinOneHourPercentBoth']. "%\n"
			. "Both Confirm and Long Reg Within Two Hours:\t". $result['withinTwoHoursPercentBoth']. "%\n"
			. "Any Within One Hour:\t". $result['withinOneHourPercentAny'] . "%\n"
			. "Any Within Two Hours:\t". $result['withinTwoHoursPercentAny'] . "%\n";
	return $s;
}